package com.meida.module.bus.provider.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.meida.common.base.entity.EntityMap;
import com.meida.common.utils.RedisUtils;
import com.meida.module.bus.client.entity.BusVipUser;
import com.meida.module.bus.client.entity.VipType;
import com.meida.module.bus.client.enums.ExamineStatusEnum;
import com.meida.module.bus.client.enums.OrderTypeEnum;
import com.meida.module.bus.provider.service.BusPayBalanceService;
import com.meida.module.bus.provider.service.BusVipUserService;
import com.meida.module.order.client.entity.OrderInfo;
import com.meida.module.product.client.entity.ProdProduct;
import com.meida.module.system.provider.service.SysDictDataService;
import com.meida.module.user.provider.service.AppUserService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 返利计算
 * @ClassName RebateLogicService
 * @date: 2022.06.25 14:45
 * @Author: ldd
 */
@Component
@Log4j2
public class RebateLogicService {

    @Resource
    private RedisUtils redisUtils;

    @Autowired
    SysDictDataService dictDataService;

    @Lazy
    @Resource
    private BusVipUserService busVipUserService;
    @Lazy
    @Resource
    private BusPayBalanceService busPayBalanceService;
    @Lazy
    @Resource
    AppUserService appUserService;

    /**
     * description: 分佣计算
     * date: 2022年-06月-20日 15:41
     * author: ldd
     *
     * @param product      商品
     * @param orderInfo    订单
     * @param payUser      购买用户
     * @param superiorUser 下单人的上级
     * @return void
     */
    @Async("myTaskAsyncPool")
    public void buyCommodity(OrderInfo orderInfo, ProdProduct product, EntityMap payUser, EntityMap superiorUser) {
        int superiorUserType = !"".equals(superiorUser.get("vipTypeId") + "") && !"null".equals(superiorUser.get("vipTypeId") + "") ? Integer.parseInt(superiorUser.get("vipTypeId") + "") : 0;
        int vipUserType = !"".equals(payUser.get("vipTypeId") + "") && !"null".equals(payUser.get("vipTypeId") + "") ? Integer.parseInt(payUser.get("vipTypeId") + "") : 0;
        //返佣
        BigDecimal rebate = BigDecimal.valueOf(0);
        //返佣点
        BigDecimal rebateConf = BigDecimal.valueOf(0);
        //获取分佣 /分红 配置
        JSONObject commissionObj = JSON.parseObject(redisUtils.getConfig("COMMISSION"));
        if (superiorUserType >= 1) {
            if (superiorUserType == 1) {
                rebateConf = commissionObj.getBigDecimal("product");
            } else {
                rebateConf = commissionObj.getBigDecimal("vip2product");
            }
            //>>>> 返佣
            rebate = product.getProductPrice().multiply(rebateConf);
            if (rebate.compareTo(BigDecimal.valueOf(0)) > 0) {
                log.info("返佣公式 rebate{} = product.getProductPrice(){}.multiply(rebateConf){}", rebate, product.getProductPrice(), rebateConf);
                busPayBalanceService.addBalance(superiorUser.getLong("userId"), superiorUser.get("userType"), rebate, orderInfo.getOrderNo(), OrderTypeEnum.OrderType20.getCode(), ExamineStatusEnum.finsh.getValue(), orderInfo.getOrderId(), "购买产品", payUser.get("fullName") + "成功购买【" + orderInfo.getOrderTitle() + "】返佣", payUser.getLong("userId"));
            }
            //<<<< 返佣
        }
        if (vipUserType > 1) {
            BusVipUser vipUserPay = busVipUserService.getByUserId(payUser.get("userId"));
            JSONObject bonusObj = JSON.parseObject(redisUtils.getConfig("PRODUCT_BONUS"));
            //同组分红
            BigDecimal bonus = BigDecimal.valueOf(0);
            //临组分红
            BigDecimal temBonus = BigDecimal.valueOf(0);
            //分红点
            BigDecimal sameGroupConf = bonusObj.getBigDecimal("sameGroup");
            BigDecimal differentGroupConf = bonusObj.getBigDecimal("differentGroup");
            BigDecimal temporaryGroupConf = bonusObj.getBigDecimal("temporaryGroup");
            BigDecimal agvGroupConf = bonusObj.getBigDecimal("agvGroup");
            //    购买用户 vip级别以上 进入分红
            //
            // 都是合伙人 下单人和下单人的上级 是否同组
            if (ObjectUtil.isNotNull(vipUserPay) && StrUtil.isNotEmpty(vipUserPay.getGroupNum())) {
                String[] payUserArr = vipUserPay.getGroupNum().split("-");
                //同组分红
                BigDecimal sameGroupBonus = (product.getProductPrice().subtract(rebate)).multiply(sameGroupConf);
                //   购买人所在组分红
                List<BusVipUser> busVipUserList = busVipUserService.getBusVipUserListByVipGroupId(payUserArr[0]);
                if (CollUtil.isNotEmpty(busVipUserList)) {
                    //组内人数
                    BigDecimal rank = BigDecimal.valueOf(busVipUserList.size());
                    bonus = busVipUserList.size() == 100 ? sameGroupBonus.divide(rank) : sameGroupBonus.divide(rank, RoundingMode.HALF_UP);
                    log.info("同组分红公式 bonus{} = (product.getProductPrice(){}.subtract(rebate{})).multiply(sameGroupConf{}).divide(rank{}, RoundingMode.HALF_UP)", bonus, product.getProductPrice(), rebate, sameGroupConf, rank);
                    for (BusVipUser v : busVipUserList) {
                        busPayBalanceService.addBalance(v.getUserId(), appUserService.getById(v.getUserId()).getUserType(), bonus, orderInfo.getOrderNo(), OrderTypeEnum.OrderType30.getCode(), ExamineStatusEnum.finsh.getValue(), orderInfo.getOrderId(), "购买产品", payUser.get("fullName") + "成功购买【" + orderInfo.getOrderTitle() + "】同组分红", payUser.getLong("userId"));
                    }
                }
                // 购买人临组
                String payUserGroup = payUserArr[0];
                JSONObject object = JSON.parseObject(redisUtils.getConfig("PARTNER_GROUP_NUM"));
                String groupObj = object.getString("group");
                //非第一组
                if (groupObj.indexOf(payUserGroup) > 0) {
                    String substring = groupObj.substring(0, (groupObj.indexOf(payUserGroup) - 1));
                    substring = substring.substring(substring.length() - 1);
                    if (!payUserGroup.equals(substring)) {
                        //临组
                        temBonus = (product.getProductPrice().subtract(rebate).subtract(sameGroupBonus)).multiply(temporaryGroupConf);
                        BigDecimal divideTemBonus = temBonus.divide(BigDecimal.valueOf(100));
                        //临组所有人
                        List<BusVipUser> busVipUserList1 = busVipUserService.getBusVipUserListByVipGroupId(substring);
                        if (CollUtil.isNotEmpty(busVipUserList1)) {
                            log.info("临组分红公式 divideTemBonus{} =(product.getProductPrice(){} .subtract(rebate{} ).subtract(sameGroupBonus{} )).multiply(temporaryGroupConf{} ).divide(BigDecimal.valueOf(100, BigDecimal.ROUND_HALF_UP))", divideTemBonus, product.getProductPrice(), rebate, sameGroupBonus, temporaryGroupConf);
                            for (BusVipUser v : busVipUserList1) {
                                busPayBalanceService.addBalance(v.getUserId(), appUserService.getById(v.getUserId()).getUserType(), divideTemBonus, orderInfo.getOrderNo(), OrderTypeEnum.OrderType30.getCode(), ExamineStatusEnum.finsh.getValue(), orderInfo.getOrderId(), "购买产品", payUser.get("fullName") + "成功购买【" + orderInfo.getOrderTitle() + "】临组分红", payUser.getLong("userId"));
                            }
                        }
                    }
                }
                //运营中心
                List<BusVipUser> busVipUserList3 = busVipUserService.getBusVipUserListByVipTypeId(3L, "");
                if (CollUtil.isNotEmpty(busVipUserList3)) {
                    BigDecimal multiply = (product.getProductPrice().subtract(rebate).subtract(sameGroupBonus).subtract(temBonus)).multiply(agvGroupConf);
                    BigDecimal divide = busVipUserList3.size() == 100 ? multiply.divide(new BigDecimal(100)) : multiply.divide(BigDecimal.valueOf(busVipUserList3.size()), BigDecimal.ROUND_HALF_UP);
                    log.info("运营中心公式 divide{} =(product.getProductPrice(){}.subtract(rebate){}.subtract(sameGroupBonus){}.subtract(temBonus){}).multiply(agvGroupConf{}).divide(BigDecimal.valueOf(busVipUserList.size(){}), BigDecimal.ROUND_HALF_UP)", divide, product.getProductPrice(), rebate, sameGroupBonus, temBonus, agvGroupConf, busVipUserList3.size());
                    for (BusVipUser v : busVipUserList3) {
                        busPayBalanceService.addBalance(v.getUserId(), appUserService.getById(v.getUserId()).getUserType(), divide, orderInfo.getOrderNo().toString(), OrderTypeEnum.OrderType30.getCode(), ExamineStatusEnum.finsh.getValue(), orderInfo.getOrderId(), "购买产品", payUser.get("fullName") + "成功购买【" + orderInfo.getOrderTitle() + "】平均分红", payUser.getLong("userId"));
                    }
                }
            }
        }
    }


    /**
     * description: 分佣计算
     * date: 2022年-06月-20日 15:41
     * author: ldd
     *
     * @param vip          会员
     * @param busVipUser   会员关系表
     * @param payUser      购买用户
     * @param superiorUser 下单人的上级
     * @return void
     */
    @Async("myTaskAsyncPool")
    public void buyVip(VipType vip, EntityMap payUser, EntityMap superiorUser, BusVipUser busVipUser) {
        int superiorUserType = superiorUser == null ? 0 : (!"".equals(superiorUser.get("vipTypeId") + "") && !"null".equals(superiorUser.get("vipTypeId") + "") ? Integer.parseInt(superiorUser.get("vipTypeId") + "") : 0);
        int vipUserType = !"".equals(payUser.get("vipTypeId") + "") && !"null".equals(payUser.get("vipTypeId") + "") ? Integer.parseInt(payUser.get("vipTypeId") + "") : 0;
        //返佣
        BigDecimal rebate = BigDecimal.valueOf(0);
        JSONObject commissionObj = JSON.parseObject(redisUtils.getConfig("COMMISSION"));
        //返佣点
        BigDecimal rebateConf = BigDecimal.valueOf(0);
        if (superiorUserType >= 1) {
            if (superiorUserType == 1) {
                if (vipUserType == 1) {
                    rebateConf = commissionObj.getBigDecimal("vip");
                }
            } else {
                if (vipUserType == 1) {
                    rebateConf = commissionObj.getBigDecimal("vip2vip");
                } else if (vipUserType == 2) {
                    rebateConf = commissionObj.getBigDecimal("vip2vip2");
                } else if (vipUserType == 3) {
                    return;
                }
            }
            //>>>> 返佣
            rebate = vip.getPrePrice().multiply(rebateConf);
            if (rebate.compareTo(BigDecimal.valueOf(0)) > 0) {
                busPayBalanceService.addBalance(superiorUser.getLong("userId"), superiorUser.get("userType"), rebate, busVipUser.getVipId().toString(), OrderTypeEnum.OrderType20.getCode(), ExamineStatusEnum.finsh.getValue(), busVipUser.getVipId(), "邀请好友", "邀请" + payUser.get("fullName") + "加入【再少点】" + vip.getVipName() + "】返佣", payUser.getLong("userId"));
            }
            //<<<< 返佣
        }
        if (vipUserType > 1) {
            JSONObject bonusObj = JSON.parseObject(redisUtils.getConfig("VIP_BONUS"));
            //同组分红
            BigDecimal bonus = BigDecimal.valueOf(0);
            //临组分红
            BigDecimal temBonus = BigDecimal.valueOf(0);
            //分红点
            BigDecimal sameGroupConf = bonusObj.getBigDecimal("sameGroup");
            BigDecimal differentGroupConf = bonusObj.getBigDecimal("differentGroup");
            BigDecimal temporaryGroupConf = bonusObj.getBigDecimal("temporaryGroup");
            BigDecimal agvGroupConf = bonusObj.getBigDecimal("agvGroup");
            //    购买用户 vip级别以上 进入分红
            BusVipUser vipUserPay = busVipUserService.getByUserId(payUser.get("userId"));
            if (ObjectUtil.isNotNull(vipUserPay) && StrUtil.isNotBlank(vipUserPay.getGroupNum())) {
                String[] payUserArr = vipUserPay.getGroupNum().split("-");
                //排位
                int rankLeng = Integer.parseInt(payUserArr[1]) - 1;
                BigDecimal sameGroupBonus = new BigDecimal(0);
                if (rankLeng > 0) {
                    List<BusVipUser> busVipUserList = busVipUserService.getBusVipUserListByVipGroupId(payUserArr[0]);
                    List<BusVipUser> collect = busVipUserList.stream().filter(v -> vipUserPay.getUserId().equals(vipUserPay.getUserId())).collect(Collectors.toList());
                    //避免本组只有自己
                    if (CollUtil.isNotEmpty(busVipUserList) && CollUtil.isNotEmpty(collect)) {
                        //组内人数
                        BigDecimal rank = BigDecimal.valueOf(collect.size());
                        //同组分红
                        sameGroupBonus = (vip.getPrePrice().subtract(rebate)).multiply(sameGroupConf);
                        //   购买人所在组分红
                        bonus = sameGroupBonus.divide(rank, RoundingMode.HALF_UP);
                        for (BusVipUser v : collect) {
                            busPayBalanceService.addBalance(v.getUserId(), appUserService.getById(v.getUserId()).getUserType(), bonus, busVipUser.getVipId().toString(), OrderTypeEnum.OrderType30.getCode(), ExamineStatusEnum.finsh.getValue(), busVipUser.getVipId(), "邀请好友", "邀请" + payUser.get("fullName") + "加入【再少点】" + vip.getVipName() + "】同组分红", payUser.getLong("userId"));
                        }
                    }
                }
                // 购买人临组
                String payUserGroup = payUserArr[0];
                JSONObject object = JSON.parseObject(redisUtils.getConfig("PARTNER_GROUP_NUM"));
                String groupObj = object.getString("group");
                //非第一组
                if (groupObj.indexOf(payUserGroup) > 0) {
                    String substring = groupObj.substring(0, (groupObj.indexOf(payUserGroup) - 1));
                    substring = substring.substring(substring.length() - 1);
                    if (!payUserGroup.equals(substring)) {
                        //临组
                        temBonus = (vip.getPrePrice().subtract(rebate).subtract(sameGroupBonus)).multiply(temporaryGroupConf);
                        BigDecimal divideTemBonus = temBonus.divide(BigDecimal.valueOf(100));
                        //临组所有人
                        List<BusVipUser> busVipUserList1 = busVipUserService.getBusVipUserListByVipGroupId(substring);
                        if (CollUtil.isNotEmpty(busVipUserList1)) {
                            for (BusVipUser v : busVipUserList1) {
                                busPayBalanceService.addBalance(v.getUserId(), appUserService.getById(v.getUserId()).getUserType(), divideTemBonus, busVipUser.getVipId().toString(), OrderTypeEnum.OrderType30.getCode(), ExamineStatusEnum.finsh.getValue(), busVipUser.getVipId(), "邀请好友", "邀请" + payUser.get("fullName") + "加入【再少点】" + vip.getVipName() + "】临组分红", payUser.getLong("userId"));
                            }
                        }
                    }
                }
                //运营中心
                List<BusVipUser> busVipUserList3 = busVipUserService.getBusVipUserListByVipTypeId(3L, "");
                if (CollUtil.isNotEmpty(busVipUserList3)) {
                    BigDecimal multiply = (vip.getPrePrice().subtract(rebate).subtract(sameGroupBonus).subtract(temBonus)).multiply(agvGroupConf);
                    BigDecimal divide = busVipUserList3.size() == 100 ? multiply.divide(new BigDecimal(100)) : multiply.divide(new BigDecimal(busVipUserList3.size()), BigDecimal.ROUND_HALF_UP);
                    for (BusVipUser v : busVipUserList3) {
                        busPayBalanceService.addBalance(v.getUserId(), appUserService.getById(v.getUserId()).getUserType(), divide, busVipUser.getVipId().toString(), OrderTypeEnum.OrderType40.getCode(), ExamineStatusEnum.finsh.getValue(), busVipUser.getVipId(), "邀请好友", "邀请" + payUser.get("fullName") + "加入【再少点】" + vip.getVipName() + "】平均分红", payUser.getLong("userId"));
                    }
                }
            }
        }
    }

    /**
     * description: 加权分红计算
     * date: 2022年-06月-20日 15:41
     * author: ldd
     *
     * @param money 提现金额
     * @return void
     */
    @Async("myTaskAsyncPool")
    public void calculateWeighting(BigDecimal money, String userName, Long userId, Long outTradeNo) {
        if (money.compareTo(BigDecimal.valueOf(0)) == 0) {
            return;
        }
        //比例
        JSONObject obj = JSON.parseObject(redisUtils.getConfig("WEIGHTING"));

        BigDecimal weighting = obj.getBigDecimal("weighting");
        List<BusVipUser> busVipUserList = busVipUserService.getBusVipUserListByVipTypeId(3L, "");
        if (CollUtil.isNotEmpty(busVipUserList)) {
            BigDecimal divide = money.multiply(weighting).divide(BigDecimal.valueOf(busVipUserList.size()), BigDecimal.ROUND_HALF_UP);
            for (BusVipUser v : busVipUserList) {
                busPayBalanceService.addBalance(v.getUserId(), appUserService.getById(v.getUserId()).getUserType(), divide, outTradeNo.toString(), OrderTypeEnum.OrderType40.getCode(), ExamineStatusEnum.finsh.getValue(), outTradeNo, "提现分红", "【" + userName + "】成功提现分红", userId);
            }
        }

    }

}
